import React, { useEffect, useState } from 'react';
import { Button, Icon, Input, Table, message, Popconfirm, Tooltip } from 'antd';
import runningImg from '@containers/system-update/images/running.png';
import stopImg from '@containers/system-update/images/stop.png';
import offlineImg from '@containers/system-update/images/offline.png';
import moment from 'moment';
import * as API from '@api/system';
import './index.less';
const prefixCls = 'adapter-manage';
const Search = Input.Search;
import AddModel from './components/addmodal';
import cmdb from '@images/adapter/cmdb.png';

const productDist = {
  cmdb: cmdb
};

const connectionStatus = [
  { text: '运行中', value: 'on' },
  { text: '连接异常', value: 'off' },
  { text: '禁用', value: 'disable' }
];
const enableStatus = [{ text: '已启用', value: true }, { text: '已禁用', value: false }];
const connectionStatusImg = {
  on: runningImg,
  off: offlineImg,
  disable: stopImg
};
const AdapterManage = () => {
  const [filter, setFilter] = useState({ page: 1, pageSize: 10 });
  const [count, setCount] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [tableLoading, setTableLoading] = useState(false);
  const [detail, setDetail] = useState();
  const [visible, setVisible] = useState();
  const [manufacturerList, setManufacturerList] = useState();
  const [manufacturerFiledList, setManufacturerFiledList] = useState();

  const getAdapterList = async query => {
    setTableLoading(true);
    try {
      const {
        data: { data }
      } = await API.getAdapterList(query);
      const { list, count } = data;
      setTableData(list);
      setCount(count);
    } catch (e) {
      message.error('适配器列表请求失败');
    }
    setTableLoading(false);
  };

  const successDeleteAdapter = () => {
    message.success('删除成功');
    let cloneFilter = { ...filter };
    const { page, pageSize } = cloneFilter;
    if ((count - 1) / pageSize - page === -1) {
      cloneFilter.page = 1;
      cloneFilter.pageSize = 10;
      setFilter({ ...cloneFilter });
    }
    getAdapterList({ ...cloneFilter });
  };
  const deleteAdapter = id => {
    API.deleteAdapter({ id })
      .then(() => successDeleteAdapter())
      .catch(() => {
        message.error('删除失败');
      });
  };

  const onSearchChange = e => {
    getAdapterList({ ...filter, search: e, page: 1 });
  };

  // 厂商列表下拉
  const getAdapterManufacturerList = async () => {
    const res = await API.getAdapterManufacturerList();
    setManufacturerList(res?.data?.data);
  };

  // 厂商字段列表
  const getAdapterManufacturerFieldList = async () => {
    const res = await API.getAdapterManufacturerFieldList();
    setManufacturerFiledList(res?.data?.data);
  };

  useEffect(() => {
    getAdapterList({ ...filter });
    getAdapterManufacturerList();
    getAdapterManufacturerFieldList();
  }, []);

  const onTableChange = (pagination, filter, sorter) => {
    const originFilter = { ...filter };
    const { current, pageSize } = pagination;
    originFilter.page = current;
    originFilter.pageSize = pageSize;
    if (sorter.field) {
      originFilter[sorter.field] = sorter.order === 'ascend' ? 'ASC' : 'DESC';
    }
    setFilter({ ...originFilter, ...filter });
    getAdapterList({ ...originFilter, ...filter });
  };

  const columns = [
    {
      title: '来源',
      dataIndex: 'adapterType',
      width: 180,
      render: key => <img src={productDist[key]} width={130} height={60} />,
      filters: manufacturerList,
      filterMultiple: true,
      filteredValue:
        filter.adapterType && filter.adapterType.length !== 0 ? [filter.adapterType] : []
    },
    {
      title: '名称',
      dataIndex: 'name'
    },
    {
      title: '地址',
      dataIndex: 'customData',
      render: key => {
        return key['address'] || '-';
      }
    },
    {
      title: '连接状态',
      dataIndex: 'status',
      className: 'connection-status',
      render: key => {
        return (
          <Tooltip
            className="info"
            placement="right"
            overlayClassName={`${prefixCls}-page-title-desc`}
            title={connectionStatus.find(r => r.value === key)?.text}
          >
            <img src={connectionStatusImg[key]} width={40} />
          </Tooltip>
        );
      },
      filters: connectionStatus,
      filterMultiple: false,
      filteredValue: filter.status
    },
    {
      title: '启用状态',
      dataIndex: 'enable',
      className: 'vulner-is-build-in',
      render: enable => {
        if (enable) {
          return (
            <>
              <Icon
                type="check-circle"
                theme="filled"
                style={{ marginRight: 5, color: '#11AB4E' }}
              />
              已启用
            </>
          );
        } else {
          return (
            <>
              <Icon type="minus-circle" theme="filled" style={{ marginRight: 5 }} />
              已禁用
            </>
          );
        }
      },
      filters: enableStatus,
      filterMultiple: false,
      filteredValue: filter.enable
    },
    {
      title: '创建时间',
      dataIndex: 'created',
      render: created => moment(created).format('YYYY-MM-DD HH:mm:ss'),
      sorter: (a, b) => a.created - b.created
    },
    {
      title: '数据更新时间',
      dataIndex: 'dataUpdated',
      render: dataUpdated => {
        if (!dataUpdated) {
          return '-';
        }
        const timerDate = new Date(dataUpdated);
        const currentDate = new Date();
        const differenceMs = currentDate - timerDate;
        if (differenceMs === 0) {
          return '刚刚';
        }
        const differenceSeconds = Math.floor(differenceMs / 1000 / 60);
        if (differenceSeconds <= 0) {
          return '-';
        }
        if (differenceSeconds < 60) {
          return differenceSeconds + '分钟前';
        } else if (differenceSeconds < 24 * 60) {
          return Math.floor(differenceSeconds / 60) + '小时前';
        } else {
          return Math.floor(differenceSeconds / (24 * 60)) + '天前';
        }
      },
      sorter: (a, b) => a.dataUpdated - b.dataUpdated
    },
    {
      title: '操作',
      render: item => (
        <div>
          <a
            className="be-color"
            onClick={() => {
              setDetail(item);
              setVisible(true);
            }}
          >
            编辑
          </a>
          <Popconfirm
            placement="bottomRight"
            title={'确定删除吗?删除该适配器后将不会自动获取该适配器下的资产数据'}
            onConfirm={() => deleteAdapter(item._id)}
            okText="确定"
            cancelText="取消"
          >
            <a style={{ marginLeft: 10, color: '#F04038' }}>删除</a>
          </Popconfirm>
        </div>
      )
    }
  ];
  const pagination = {
    total: count,
    current: filter.page,
    pageSize: filter.pageSize,
    showQuickJumper: true,
    pageSizeOptions: ['10', '20', '50', '100'],
    showSizeChanger: true,
    showTotal: num => `共 ${num} 条`,
    size: 'small'
  };

  return (
    <div className={prefixCls}>
      <div className={`${prefixCls}-page-title`}>
        适配器管理
        <Tooltip
          className="info"
          placement="right"
          overlayClassName={`${prefixCls}-page-title-desc`}
          title="将通过对相关适配器配置分析，自动获取该适配器下的资产数据作为新发现的资产补充到用户资产列表。"
        >
          <Icon type="exclamation-circle" />
        </Tooltip>
      </div>

      <div className={`${prefixCls}-operate`}>
        <div>
          <Button type="primary" onClick={() => setVisible(true, {})}>
            添加适配器
          </Button>
        </div>
        <div>
          <Search
            value={filter.search}
            enterButton
            placeholder="请输入地址、名称等搜索"
            onChange={value => setFilter({ ...filter, search: value.target.value })}
            onSearch={onSearchChange}
          />
        </div>
      </div>

      <div>
        <div className={`${prefixCls}-header-count`}>共有 “{count}” 个设备</div>
        <Table
          loading={tableLoading}
          columns={columns}
          pagination={pagination}
          dataSource={tableData}
          onChange={onTableChange}
        />
      </div>

      <AddModel
        detail={detail}
        visible={visible}
        setDetail={setDetail}
        setVisible={setVisible}
        manufacturerFiledList={manufacturerFiledList}
        manufacturerList={manufacturerList}
        onChange={() => getAdapterList({ ...filter })}
      />
    </div>
  );
};
export default AdapterManage;
